<template>
  <view class="container">
    <!-- 第一步：扫描二维码/条形码 -->
    <view class="step">
      <view class="step-header">
        <text class="step-number">1</text>
        <text class="step-title">扫描燃气表二维码/条形码</text>
      </view>
      <button class="btn primary" @click="scanCode">扫描二维码/条形码</button>
      <view class="result-box" v-if="qrCodeContent">
        <text class="result-label">扫描结果：{{ qrCodeContent }}</text>
      </view>
    </view>

    <!-- 第二步：搜索燃气表蓝牙 -->
    <view class="step">
      <view class="step-header">
        <text class="step-number">2</text>
        <text class="step-title">搜索燃气表蓝牙</text>
      </view>
      <button class="btn primary" @click="searchGasMeter" :disabled="!qrCodeContent">搜索燃气表蓝牙</button>
      <view class="device-info" v-if="gasMeterDevice.name">
        <text class="device-name">设备名称：{{ gasMeterDevice.name }}</text>
        <text class="device-mac">MAC地址：{{ gasMeterDevice.deviceId }}</text>
      </view>
      <view class="empty-tip" v-else-if="searchingGasMeter">
        <text>正在搜索中...</text>
      </view>
    </view>

    <!-- 第三步：搜索报警器蓝牙 -->
    <view class="step">
      <view class="step-header">
        <text class="step-number">3</text>
        <text class="step-title">搜索报警器蓝牙</text>
      </view>
      <button class="btn primary" @click="searchAlarm" :disabled="!gasMeterDevice.deviceId">搜索报警器蓝牙</button>
      <view class="alarm-list" v-if="alarmDevices.length > 0">
        <text class="list-title">可连接的报警器：</text>
        <view class="alarm-item" v-for="(item, index) in alarmDevices" :key="index" @click="connectAlarm(item)">
          <text class="alarm-name">{{ item.name }}</text>
          <text class="alarm-mac">{{ gasMeterDevice.deviceId }}</text>
          <text class="alarm-status" :class="{ connected: item.connected }">
            {{ item.connected ? '点击断开' : '点击连接' }}
          </text>
        </view>
      </view>
      <view class="empty-tip" v-else-if="searchingAlarm">
        <text>正在搜索报警器...</text>
      </view>
    </view>

    <!-- 第四步：发送数据 -->
    <view class="step" v-if="connectedAlarm">
      <view class="step-header">
        <text class="step-number">4</text>
        <text class="step-title">发送燃气表信息</text>
      </view>
      <button class="btn success" @click="sendGasMeterInfoNew">发送燃气表MAC地址</button>
      <view class="send-result" v-if="sendResult">
        <text>{{ sendResult }}</text>
      </view>
    </view>

    <!-- 新增通信日志区域 -->
    <view class="comm-log-box">
      <text class="log-title">通信日志</text>
      <scroll-view class="log-list" scroll-y>
        <view class="log-item" v-for="(log, index) in commLogs" :key="index">
          <text class="log-time">{{ log.time }}</text>
          <text class="log-content" :class="{'receive-log': log.type === 'receive'}">
            {{ log.content }}
          </text>
        </view>
      </scroll-view>
    </view>


  </view>
</template>

<script>

export default {
  data() {
    return {
      qrCodeContent: '', // 扫描的二维码/条形码内容
      gasMeterDevice: {}, // 匹配的燃气表蓝牙设备
      alarmDevices: [], // 找到的报警器设备列表
      connectedAlarm: null, // 当前连接的报警器
      sendResult: '', // 发送结果信息
      statusText: '准备就绪', // 状态栏文本
      searchingGasMeter: false, // 是否正在搜索燃气表
      searchingAlarm: false, // 是否正在搜索报警器
      stopSearchTimer: null, // 停止搜索的定时器
      commLogs: [], // 通信日志
      notifyCharacteristic: null ,// 用于存储通知特征值
	  receiveServiceUUID:null,
	  receiveCharacteristicId: null,
	  sendServiceUUID:null,
	  sendCharacteristicId: null,
    };
  },
  methods: {
	  // 扫码设备二维码并跳转安装界面
	  scanDeviceCode(){
		  uni.scanCode({
		    onlyFromCamera: true,
		    scanType: ['qrCode', 'barCode'],
		    success: (res) => {
				if(res.result){
					var imei;
					if(res.result.length == 68){
						imei = res.result.substr(24,15);
					}else {
						if (res.result.startsWith("02_NB_") || res.result.startsWith("02_4G_") || res.result.startsWith("02_2G_")) {
						  imei = res.result.substring(6);
						}
					}
					if(imei && imei.length == 15){
						imei += '0';
					}
					if(imei && imei.length == 16){
						uni.navigateTo({
							url: `/homePages/installDevice/index?imei=` + imei,
						})
					}else{
						this.statusText = '二维码格式错误，请检查！';
						this.addCommLog('system', this.statusText);
					}
					
				}else{
					this.statusText = '二维码格式错误，请检查！';
					this.addCommLog('system', this.statusText);
				}
		    },
		    fail: (err) => {
		      this.statusText = '扫描设备二维码失败: ' + (err.errMsg || '未知错误');
		      this.addCommLog('system', this.statusText);
		      console.error('扫描设备二维码失败:', err);
		    }
		  });
	  },
    // 扫描二维码/条形码
    scanCode() {
      this.statusText = '准备扫描...';
	  this.addCommLog('system', this.statusText);
      uni.scanCode({
        onlyFromCamera: true,
        scanType: ['qrCode', 'barCode'],
        success: (res) => {
		  this.connectedAlarm = false;
		  this.sendResult = "";
		  this.alarmDevices = [];	
		  this.gasMeterDevice = {};
		 
          this.qrCodeContent = res.result;
          this.gasMeterDevice = {};
          this.alarmDevices = [];
          this.connectedAlarm = null;
          this.statusText = `扫描成功: ${res.result}`;
	      this.addCommLog('system', this.statusText);
        },
        fail: (err) => {
          this.statusText = '扫描失败: ' + (err.errMsg || '未知错误');
	      this.addCommLog('system', this.statusText);
          console.error('扫描失败:', err);
        }
      });
    },

    // 搜索燃气表蓝牙设备
    searchGasMeter() {
	  this.connectedAlarm = false;
	  this.sendResult = "";
	  this.alarmDevices = [];
      if (!this.qrCodeContent || this.qrCodeContent.length < 6) {
        uni.showToast({
          title: '二维码/条形码无效',
          icon: 'none'
        });
        return;
      }

      this.stopBluetoothSearch();

      this.statusText = '正在初始化蓝牙...';
	  this.addCommLog('system', this.statusText);
      this.searchingGasMeter = true;
      this.gasMeterDevice = {};

      // 获取后6位用于匹配
      const suffix = this.qrCodeContent.slice(-6);

      // 开启蓝牙适配器
      uni.openBluetoothAdapter({
        success: () => {
          this.statusText = '正在搜索燃气表蓝牙...';
	      this.addCommLog('system', this.statusText);

          // 开始搜索设备
          uni.startBluetoothDevicesDiscovery({
            allowDuplicatesKey: true, // 允许重复上报同一设备
            success: () => {
              this.statusText = '搜索中...';
	          this.addCommLog('system', this.statusText);
			  
              // 监听发现新设备
              uni.onBluetoothDeviceFound((devices) => {
                if (!Array.isArray(devices)) {
                  devices = [devices];
                }

                devices.forEach(device => {
                  if (device.devices && device.devices.length > 0) {
                    // 检查设备名称是否包含二维码后6位
                    if (device.devices[0].name && device.devices[0].name.includes(suffix)) {
                      this.gasMeterDevice = device.devices[0];
                      this.statusText = `找到燃气表: ${device.devices[0].name}`;
	                  this.addCommLog('system', this.statusText);
                      this.stopBluetoothSearch();
                      this.searchingGasMeter = false;
                    }
                  }
                });
              });

              // 30秒后自动停止搜索
              this.stopSearchTimer = setTimeout(() => {
                if (!this.gasMeterDevice.deviceId) {
                  this.statusText = '未找到匹配的燃气表蓝牙';
	              this.addCommLog('system', this.statusText);
                  this.stopBluetoothSearch();
                  this.searchingGasMeter = false;
                }
              }, 20000);
            },
            fail: (err) => {
              this.statusText = '搜索失败: ' + (err.errMsg || '未知错误');
	          this.addCommLog('system', this.statusText);
              this.searchingGasMeter = false;
              console.error('蓝牙搜索失败:', err);
            }
          });
        },
        fail: (err) => {
          this.statusText = '蓝牙初始化失败: ' + (err.errMsg || '未知错误');
	      this.addCommLog('system', this.statusText);
          this.searchingGasMeter = false;
          console.error('蓝牙适配器打开失败:', err);
          this.showBluetoothError(err);
        }
      });
    },

    // 搜索报警器蓝牙设备
    searchAlarm() {
	  this.connectedAlarm = false;
	  this.sendResult = "";
	  this.alarmDevices = [];
      if (!this.gasMeterDevice.deviceId) {
        uni.showToast({
          title: '请先找到燃气表设备',
          icon: 'none'
        });
        return;
      }
      this.stopBluetoothSearch();
      this.statusText = '正在搜索报警器...';
	  this.addCommLog('system', this.statusText);
      this.searchingAlarm = true;
      this.alarmDevices = [];

      uni.startBluetoothDevicesDiscovery({
        allowDuplicatesKey: true, // 允许重复上报同一设备
        success: () => {
          this.statusText = '搜索报警器中...';
	      this.addCommLog('system', this.statusText);

          // 监听发现新设备
          uni.onBluetoothDeviceFound((devices) => {
            if (!Array.isArray(devices)) {
              devices = [devices];
            }

            devices.forEach(device => {
              if (device.devices && device.devices.length > 0) {
                // 检查设备名称是否包含xhs (报警器标识)
                if (device.devices[0].name && (device.devices[0].name.includes('xhsble') || 
                    device.devices[0].name.includes('XHSBLE'))) {
                  // 避免重复添加
                  const exists = this.alarmDevices.some(d => d.deviceId === device.devices[0].deviceId);
                  if (!exists) {
                    this.alarmDevices.push({
                      ...device.devices[0],
                      connected: false
                    });
                  }else{
					  // 已存在，更新 RSSI（信号强度）
					this.alarmDevices[existingIndex].RSSI = targetDevice.RSSI;
				  }
				  
				  // 按 RSSI（信号强度）降序排序（信号最强的排前面）
				  this.alarmDevices.sort((a, b) => (b.RSSI || -1000) - (a.RSSI || -1000));
                }
              }
            });
          });

          // 10秒后自动停止搜索
          this.stopSearchTimer = setTimeout(() => {
            this.statusText = this.alarmDevices.length > 0 ? 
              `找到 ${this.alarmDevices.length} 个报警器` : 
              '未找到报警器设备';
	        this.addCommLog('system', this.statusText);
            this.stopBluetoothSearch();
            this.searchingAlarm = false;
          }, 20000);
        },
        fail: (err) => {
          this.statusText = '搜索失败: ' + (err.errMsg || '未知错误');
	      this.addCommLog('system', this.statusText);
          this.searchingAlarm = false;
          console.error('报警器搜索失败:', err);
        }
      });
    },

    // 连接报警器设备
    connectAlarm(device) {
      if (device.connected) {
		  // 断开连接
		  this.statusText = `正在断开 ${device.name}...`;
		  this.addCommLog('system', this.statusText);
		  
		  uni.closeBLEConnection({
			deviceId: device.deviceId,
			success: () => {
			  this.statusText = `已断开 ${device.name}`;
			  this.addCommLog('system', this.statusText);
			  device.connected = false;
			  this.connectedAlarm = null;
			  
			  // 移除通知监听
			  uni.offBLECharacteristicValueChange();
			  
			  // 更新设备列表状态
			  this.alarmDevices = this.alarmDevices.map(d => {
				if (d.deviceId === device.deviceId) {
				  return { ...d, connected: false };
				}
				return d;
			  });
			  
			  // 重置特征值相关变量
			  this.notifyCharacteristic = null;
			  this.receiveServiceUUID = null;
			  this.receiveCharacteristicId = null;
			  this.sendServiceUUID = null;
			  this.sendCharacteristicId = null;
			},
			fail: (err) => {
			  this.statusText = `断开失败: ${err.errMsg || '未知错误'}`;
			  this.addCommLog('system', `报警器断开失败: ${err.errMsg}`);
			  device.connected = false;
			  this.connectedAlarm = null;
			}
		  });
		  return;
	  }

      this.stopBluetoothSearch();

      this.statusText = `正在连接 ${device.name}...`;
      this.addCommLog('system', this.statusText);

      uni.createBLEConnection({
        deviceId: device.deviceId,
        success: () => {
          this.statusText = `已连接 ${device.name}`;
          this.addCommLog('system', this.statusText);
          device.connected = true;
          this.connectedAlarm = device;

          // 更新设备列表状态
          this.alarmDevices = this.alarmDevices.map(d => {
            if (d.deviceId === device.deviceId) {
              return { ...d, connected: true };
            }
            return { ...d, connected: false };
          });

          // 停止搜索
          this.stopBluetoothSearch();
		  // 收消息
		  this.querySendAndReceFuture();
        },
        fail: (err) => {
          this.statusText = `连接失败: ${err.errMsg || '未知错误'}`;
          console.error('连接失败:', err);
          this.addCommLog('system', `报警器连接失败: ${err.errMsg}`);
        }
      });
    },
	
	// 查询收 发特征
	querySendAndReceFuture(){
		if (!this.connectedAlarm || !this.gasMeterDevice.deviceId) {
		  uni.showToast({
		    title: '请先连接报警器',
		    icon: 'none'
		  });
		  return;
		}
		
		this.statusText = '查询特征中...';
		this.addCommLog('system', this.statusText);
		
		this.receiveServiceUUID = null;
		this.receiveCharacteristicId = null;
		this.sendServiceUUID = null;
		this.sendCharacteristicId =null;
		
		uni.getBLEDeviceServices({
		  deviceId: this.connectedAlarm.deviceId,
		  success: (res) => {
		    if (res.services.length === 0) {
		      this.addCommLog('system', '未找到蓝牙服务');
		      return;
		    }
			
		    // 遍历所有服务查找发送特征
		    res.services.forEach(service => {
		      uni.getBLEDeviceCharacteristics({
		        deviceId: this.connectedAlarm.deviceId,
		        serviceId: service.uuid,
		        success: (chars) => {
		          // 查找发送特征 (包含fe61)
		          const writeChar = chars.characteristics.find(c =>
		            c.uuid.toLowerCase().includes('fe61')
		          );
			
		          if (writeChar) {
				    this.addCommLog('system', '找到发送特征(fe61)');
					this.sendServiceUUID = service.uuid;
					this.sendCharacteristicId =writeChar.uuid;
		          }
				  
				  // 查询接收特征
		          const writeCharReceive = chars.characteristics.find(c =>
		            c.uuid.toLowerCase().includes('fe62')
		          );
			
		          if (writeCharReceive) {
				    this.addCommLog('system', '找到接收特征(fe62)');
					this.receiveServiceUUID = service.uuid;
					this.receiveCharacteristicId =writeCharReceive.uuid;
					
					
					// 启用通知
					uni.notifyBLECharacteristicValueChange({
					  deviceId: this.connectedAlarm.deviceId,
					  serviceId: this.receiveServiceUUID,
					  characteristicId: this.receiveCharacteristicId,
					  state: true,
					  success: () => {
					    this.addCommLog('system', '已启用接收通知');
					
					    // 监听通知
					    uni.onBLECharacteristicValueChange((res) => {
						  const backArray = this.ab2Desc(res.value);
						  const backString = this.bufferToHexStr(backArray);
						  this.statusText = `收到报警器消息: ${backString}`;
						  this.addCommLog('receive', this.statusText);
						  console.info("接收数据：" + backString);
						  
						  if(backArray.length > 10 && (backArray[backArray.length - 1] & 0xff) == 0x16){
							  if ((backArray[backArray.length - 3] & 0xff) == 0x0A) {
								  // 弹窗提示写入成功
								   uni.showModal({
									  title: '操作成功',
									  content: '下发燃气表信息成功，是否跳转到安装设备界面？',
									  cancelText: '取消', // 不显示取消按钮
									  confirmText: '确定', // 确认按钮文字
									  success: (res) => {
										if (res.confirm) {
										  console.log('用户点击确认');
										  // 跳转扫码界面
										  this.scanDeviceCode();
										}else if (res.cancel) {
										  console.log('用户点击取消');
										}
									  },
										fail: (err) => { 
										  uni.showToast({
											title: '操作失败',
											icon: 'none'
										  });
										}
									});
							  }else{
								  // 弹窗提示写入失败
								   uni.showModal({
									  title: '操作成功',
									  content: '下发燃气表信息失败，请重新下发！',
									  showCancel: false, // 不显示取消按钮
									  confirmText: '取消', // 确认按钮文字
									  success: (res) => {
										if (res.confirm) {
										  console.log('用户点击取消');
										}
									  }
									});
							  }
						  }
					    });
					  },
					  fail: (err) => {
					    this.addCommLog('system', `启用接收通知失败: ${err.errMsg}`);
					  }
					});
		          }
		        },
		        fail: (err) => {
		          this.addCommLog('system', `获取特征值失败: ${err.errMsg}`);
		        }
		      });
		    });

		  },
		  fail: (err) => {
		    this.addCommLog('system', `获取服务失败: ${err.errMsg}`);
		  }
		});
	},
	
	// 发送燃气表MAC地址到报警器
	sendGasMeterInfoNew(){
		if (!this.connectedAlarm || !this.gasMeterDevice.deviceId) {
		  uni.showToast({
		    title: '请先连接报警器',
		    icon: 'none'
		  });
		  return;
		}
		
		if(!this.sendServiceUUID || !this.sendCharacteristicId){
			uni.showToast({
			  title: '未找到发送特征，请重新搜索并连接',
			  icon: 'none'
			});
			return;
		}
			
		this.statusText = '正在准备发送数据...';
		this.addCommLog('system', this.statusText);
			
		// 初始数据
		const bytes = this.hexStringToByteArray(
		  this.gasMeterDevice.deviceId.replace(/:/g, '')
		);
		const bytes3 = new Uint8Array(20); // 创建长度为 20 的字节数组
					
		// 初始化固定值
		bytes3[0] = 0x68;
		bytes3[1] = 0x51;
		bytes3[2] = 0x84;
					
		// 设置燃气表厂家信息
		if (this.gasMeterDevice.name.toUpperCase().startsWith("FRXGM")) {
		  bytes3[3] = 0;
		} else if (this.gasMeterDevice.name.toUpperCase().startsWith("ZENNER")) {
		  bytes3[3] = (1 << 4) & 0x70;
		} else if (this.gasMeterDevice.name.toUpperCase().startsWith("CHINT")) {
		  bytes3[3] = (2 << 4) & 0x70;
		} else if (this.gasMeterDevice.name.toUpperCase().startsWith("AR")) {
		  bytes3[3] = (1 << 4) & 0x70;
		} else if (this.gasMeterDevice.name.toUpperCase().startsWith("XT")) {
		  bytes3[3] = (3 << 4) & 0x70;
		} else if (this.gasMeterDevice.name.toUpperCase().startsWith("SC")) {
		  bytes3[3] = (1 << 4) & 0x70;
		} else {
		  bytes3[3] = 0;
		}
					
		// 截取表名后 6 个字符并转换为字节数组
		const itemString = this.gasMeterDevice.name.slice(-6);
		const bytes1 = this.stringToAsciiBytes(itemString);
					
		// 将 bytes1 填充到 bytes3 的第 5 位开始
		bytes3[4] = 0; // 固定值
		for (let i = 0; i < bytes1.length && i < 6; i++) {
		  bytes3[5 + i] = bytes1[i];
		}
					
		// 固定值
		bytes3[11] = 0x06;
					
		// 将 bytes 填充到 bytes3 的第 12 位开始
		for (let i = 0; i < bytes.length && i < 8; i++) {
		  bytes3[12 + i] = bytes[i];
		}
					
		// 计算校验和
		let countnumber1 = 0;
		for (let i = 0; i < bytes3.length - 2; i++) {
		  countnumber1 += bytes3[i] & 0xff;
		}
		bytes3[18] = countnumber1 & 0xff; // 校验和
		bytes3[19] = 0x16; // 固定结束符
					
					
	    // 获取ArrayBuffer
	    const arrayBuffer = bytes3.buffer;
					
		this.addCommLog('system', `发送数据: ${this.bufferToHexStr(arrayBuffer)}`);
		console.info(`发送数据: ${this.bufferToHexStr(arrayBuffer)}`)
					
		// 写入数据
		uni.writeBLECharacteristicValue({
		  deviceId: this.connectedAlarm.deviceId,
		  serviceId: this.sendServiceUUID,
		  characteristicId: this.sendCharacteristicId,
		  value: arrayBuffer,
		  success: () => {
		    this.sendResult = `成功发送燃气表MAC地址: ${this.gasMeterDevice.deviceId}`;
		    this.statusText = '数据发送成功';
		    this.addCommLog('system', this.statusText);
		  },
		  fail: (err) => {
		    this.addCommLog('system', `发送失败: ${err.errMsg},请重新连接并发送！`);
		  }
		});
	},
	
    // 添加通信日志
    addCommLog(type, content) {
      const now = new Date();
      const timeStr = `${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;

      this.commLogs.unshift({
        type,
        content,
        time: timeStr
      });

      // 限制日志数量
      if (this.commLogs.length > 50) {
        this.commLogs.pop();
      }
    },

    // 十六进制字符串转字节数组
    hexStringToByteArray(hexString) {
      const bytes = [];
      for (let i = 0; i < hexString.length; i += 2) {
        bytes.push(parseInt(hexString.substr(i, 2), 16));
      }
      return bytes;
    },
	
	// 转16进制字符串
	bufferToHexStr(buffer) {
        var hexArr = Array.prototype.map.call(
            new Uint8Array(buffer),
            function (bit) {
                return ('00' + bit.toString(16)).slice(-2)
            }
        )
        
        return hexArr.join('');
    },
    // 二进制转无符号整数
	ab2Desc(buffer) {
		var hexArr = Array.prototype.map.call(
			new Uint8Array(buffer),
			function (bit) {
				return bit
			}
		)
		return hexArr;
	},
	// ArrayBuffer转字符串
    ab2str(buffer) {
      return String.fromCharCode.apply(null, new Uint8Array(buffer));
    },

    // 字符串转ASCII字节数组
    stringToAsciiBytes(str) {
      const bytes = [];
      for (let i = 0; i < str.length; i++) {
        bytes.push(str.charCodeAt(i) & 0xFF); // 获取字符的ASCII码
      }
      return new Uint8Array(bytes);
    },

    // 停止蓝牙搜索
    stopBluetoothSearch() {
      if (this.stopSearchTimer) {
        clearTimeout(this.stopSearchTimer);
        this.stopSearchTimer = null;
      }
      uni.stopBluetoothDevicesDiscovery();
    },

    // 格式化MAC地址显示
    formatMacAddress(mac) {
      if (!mac) return '';
      // 简单的格式化，每两个字符加冒号
      return mac.match(/.{1,2}/g).join(':').toUpperCase();
    },

    // 显示蓝牙错误提示
    showBluetoothError(err) {
      let message = '蓝牙错误';

      if (err.errCode === 10000) {
        message = '蓝牙适配器未初始化';
      } else if (err.errCode === 10001) {
        message = '当前蓝牙适配器不可用';
      } else if (err.errCode === 10002) {
        message = '没有找到指定设备';
      } else if (err.errCode === 10003) {
        message = '连接失败';
      } else if (err.errCode === 10004) {
        message = '没有找到指定服务';
      } else if (err.errCode === 10005) {
        message = '没有找到指定特征值';
      } else if (err.errCode === 10006) {
        message = '当前连接已断开';
      } else if (err.errCode === 10007) {
        message = '当前特征值不支持此操作';
      } else if (err.errCode === 10008) {
        message = '其余所有系统上报的异常';
      } else if (err.errCode === 10009) {
        message = 'Android系统特有，系统版本低于4.3不支持BLE';
      }

      uni.showModal({
        title: '蓝牙错误',
        content: message,
        showCancel: false
      });
    }
  },

  onUnload() {
    // 页面卸载时停止蓝牙搜索
    this.stopBluetoothSearch();
    uni.closeBluetoothAdapter();

    // 移除蓝牙设备发现监听
    uni.offBluetoothDeviceFound();

    // 移除特征值变化监听
    uni.offBLECharacteristicValueChange();
  }
};
</script>

<style lang="scss">
.container {
  padding: 20rpx;
  display: flex;
  flex-direction: column;
}

.header {
  margin-bottom: 40rpx;
  text-align: center;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.step {
  margin-bottom: 20rpx;
  padding-left: 20rpx;
  padding-right: 20rpx;
  padding-top: 10rpx;
  padding-bottom: 10rpx;
  background-color: #fff;
  border-radius: 12rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.step-header {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.step-number {
  width: 40rpx;
  height: 40rpx;
  line-height: 40rpx;
  text-align: center;
  background-color: #007AFF;
  color: #fff;
  border-radius: 50%;
  font-size: 24rpx;
  margin-right: 15rpx;
}

.step-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.btn {
  margin-top: 20rpx;
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 8rpx;
  font-size: 28rpx;

  &.primary {
    background-color: #007AFF;
    color: #fff;
  }

  &.success {
    background-color: #4CD964;
    color: #fff;
  }

  &[disabled] {
    background-color: #f0f0f0;
    color: #999;
  }
}

.result-box {
  margin-top: 20rpx;
  padding: 20rpx;
  background-color: #f9f9f9;
  border-radius: 8rpx;
}

.result-label {
  font-size: 26rpx;
  color: #666;
  display: block;
  margin-bottom: 10rpx;
}

.result-content {
  font-size: 28rpx;
  color: #333;
  word-break: break-all;
}

.result-hint {
  font-size: 24rpx;
  color: #999;
  display: block;
  margin-top: 10rpx;
}

.device-info {
  margin-top: 20rpx;
  padding: 20rpx;
  background-color: #f9f9f9;
  border-radius: 8rpx;
}

.device-name,
.device-mac {
  font-size: 26rpx;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.empty-tip {
  margin-top: 20rpx;
  text-align: center;
  font-size: 26rpx;
  color: #999;
}

.alarm-list {
  margin-top: 20rpx;
}

.list-title {
  font-size: 26rpx;
  color: #666;
  display: block;
  margin-bottom: 15rpx;
}

.alarm-item {
  padding: 20rpx;
  margin-bottom: 15rpx;
  background-color: #f9f9f9;
  border-radius: 8rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.alarm-name {
  font-size: 26rpx;
  color: #333;
  flex: 2;
}

.alarm-mac {
  font-size: 24rpx;
  color: #666;
  flex: 3;
}

.alarm-status {
  font-size: 24rpx;
  color: #007AFF;
  flex: 1;
  text-align: right;

  &.connected {
    color: #4CD964;
  }
}

.send-result {
  margin-top: 20rpx;
  padding: 20rpx;
  background-color: #f9f9f9;
  border-radius: 8rpx;
  font-size: 26rpx;
  color: #333;
}

.status-bar {
  margin-top: 20rpx;
  padding: 15rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  font-size: 24rpx;
  color: #666;
  text-align: center;
}

/* 新增通信日志样式 */
.comm-log-box {
  margin-top: 30rpx;
  border-top: 1rpx solid #eee;
  padding-top: 20rpx;
}

.log-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 15rpx;
  display: block;
}

.log-list {
  max-height: 300rpx;
  background-color: #f9f9f9;
  border-radius: 8rpx;
  padding: 15rpx;
}

.log-item {
  margin-bottom: 12rpx;
  line-height: 1.6;
}

.log-time {
  font-size: 22rpx;
  color: #999;
  margin-right: 15rpx;
}

.log-content {
  font-size: 24rpx;
  color: #007AFF;

  &.receive-log {
    color: #4CD964;
  }
}
</style>